const packageInfo = require('./package.json');
const path = require('path');
const webpack = require('webpack');
const globals = require('./global-vars.json');
const env = process.env;

const assetDir = `static/${packageInfo.name}`;

function pathResolve(dir) {
    return path.resolve(__dirname, dir);
}

// 静态资源前缀，设置cdn等
function getPublicPath() {
    return `${env.VUE_APP_CDN || ''}/`;
}

module.exports = {
    // chainWebpack,
    chainWebpack: (config) => {
        // config.resolve.alias
        //     .set("@", pathResolve("src"))
        // element-plus 汉化
        config.plugin('normalModuleReplacementPlugin').use(new webpack.NormalModuleReplacementPlugin(
            /element-plus[\/\\]lib[\/\\]locale[\/\\]lang[\/\\]en/,
            'zh-cn.js'
        ));
        config.resolve.alias.set('@', pathResolve('src'));

        config.plugin('html').tap((args) => {
            args[0].title = '睿云中台';
            args[0].baseUrl = getPublicPath();
            args[0].static = assetDir;
            return args;
        });
        config.plugin('define').tap((args) => {
            Object.assign(args[0], globals);
            return args;
        });

        // element-plus 汉化
        config
            .plugin('normalModuleReplacementPlugin')
            .use(
                new webpack.NormalModuleReplacementPlugin(
                    /element-plus[\/\\]lib[\/\\]locale[\/\\]lang[\/\\]en/,
                    'zh-cn.js'
                )
            );

        if (process.env.NODE_ENV === 'production') {
            config.plugin('compression').use(
                new CompressionWebpackPlugin({
                    filename: '[path].gz[query]',
                    algorithm: 'gzip',
                    test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
                    threshold: 10240,
                    minRatio: 0.8
                })
            );

            config.performance
                // .hints(false)
                .maxEntrypointSize(50000000)
                .maxAssetSize(30000000)
                .assetFilter((assetFilename) => {
                    return assetFilename.endsWith('.js');
                });

            config.plugin('extract-css').tap(() => [
                {
                    filename: `${assetDir}/css/[name].[hash:8].css`,
                    chunkFilename: `${assetDir}/css/[name].[contenthash:8].chunk.css`,
                    ignoreOrder: true
                }
            ]);
        }

        config.output
            .filename(`${assetDir}/js/[name].[hash:8].js`)
            .chunkFilename(`${assetDir}/js/[name].[contenthash:8].chunk.js`);
        // 修改css输出目录

        // 修改图片输出目录
        config.module
            .rule('images')
            .test(/\.(png|jpe?g|gif|webp|ico)(\?.*)?$/)
            .use('url-loader')
            .loader(require.resolve('url-loader'))
            .tap((options) => ({
                ...options,
                publicPath: getPublicPath(),
                name: `${assetDir}/img/[name].[hash:8].[ext]`,
                fallback: {
                    ...options.fallback,
                    options: {
                        name: `${assetDir}/img/[name].[hash:8].[ext]`,
                        esModule: false
                    }
                }
            }));
        config.module
            .rule('fonts')
            .test(/\.(eot|woff|woff2|ttf)(\?.*)?$/)
            .use('url-loader')
            .loader(require.resolve('url-loader'))
            .tap((options) => {
                return {
                    ...options,
                    publicPath: getPublicPath(),
                    name: `${assetDir}/fonts/[name].[hash:8].[ext]`,
                    fallback: {
                        ...options.fallback,
                        options: {
                            name: `${assetDir}/fonts/[name].[hash:8].[ext]`,
                            esModule: false
                        }
                    }
                };
            });

        config.module
            .rule('svg')
            .test(/\.(svg)(\?.*)?/)
            .use('file-loader')
            .tap((options) => ({
                ...options,
                publicPath: getPublicPath(),
                name: `${assetDir}/img/[name].[hash:8].[ext]`
            }));
    },
    configureWebpack: {
        plugins: [
            new webpack.ProvidePlugin({
                G_transmit: [pathResolve('./src/dao/global/index.js'), 'tx'],
                G_useCodeHandlers: [pathResolve('./src/dao/global/index.js'), 'useCodeHandlers'],
                G_listenEvent: [pathResolve('./src/lib/event-center.js'), 'listenEvent'],
                G_dispatchEvent: [pathResolve('./src/lib/event-center.js'), 'dispatchEvent'],
            })
        ]
    },
    devServer: {
        disableHostCheck: true
    },
    css: {
        // extract: true,
        loaderOptions: {
            sass: {
                prependData: '@import "@/assets/styles/theme/var.scss";'
            }
        }
    },
    publicPath: getPublicPath(),
    outputDir: 'output',
    productionSourceMap: false,
    transpileDependencies: [
        '@shadom/cluster',
        '@shadom/portal',
        '@shadom/portal-plugin-http',
        '@shadom/translator',
        '@shadom/validator',
        'ch4o',
        'c2h6o'
    ]
};
